<!--
 * @Author: lwHao
 * @Date: 2020-12-19 14:33:58
 * @LastEditors: lwHao
 * @LastEditTime: 2020-12-19 15:40:58
-->
<template>
  <div>
    <el-form label-width="120px">
      <el-form-item label="资源名称">
        <el-input v-model="resouce.name"></el-input>
      </el-form-item>
      <el-form-item label="资源路径">
        <el-input v-model="resouce.url"></el-input>
      </el-form-item>
      <el-form-item label="资源分类">
        <el-select v-model="resouce.categoryId" placeholder="请选择">
          <el-option v-for="category in categorys" :key="category.id" :value="category.id" :label="category.name"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="描述">
        <el-input v-model="resouce.description" type="textarea"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button @click="$emit('cancel')">取消</el-button>
        <el-button type="primary" @click="onSubmit">确认</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts">
import Vue from 'vue'
import { getResourceCategories } from '@/services/resource-category'
import { getResources, saveOrUpdateResources } from '@/services/resource'

export default Vue.extend({
  name: 'CreateOrEditResource',
  props: {
    resourceId: String
  },
  data () {
    return {
      resouce: {
        name: '',
        categoryId: '',
        url: '',
        description: ''
      },
      categorys: []
    }
  },
  created () {
    // 如果是编辑操作，则根据角色 ID 加载展示角色信息
    if (this.resourceId) {
      this.loadResource()
    }
    this.loadCategory()
  },
  methods: {
    async loadCategory () {
      const { data } = await getResourceCategories()
      this.categorys = data.data
    },

    async loadResource () {
      const { data } = await getResources(this.resourceId)
      this.resouce = data.data
    },

    async onSubmit () {
      await saveOrUpdateResources(this.resouce)
      this.$message.success(this.resourceId ? '修改成功' : '操作成功')
      this.$emit('success')
    }
  }
})
</script>

<style>

</style>
